package com.example.project.controller;

import com.example.project.model.Sale;
import com.example.project.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class SaleController {
    @Autowired
    private SaleService saleService;

    //主页面
    /* @GetMapping("/")
    public String viewHomePage(Model model) {
        model.addAttribute("listSale", saleService.getAllSale());
        return "index";
    }*/
    @GetMapping("/")
    public String viewHomePage(Model model) {
        return findPaginated(1, "id", "asc", model);
    }

    //添加销售数据
    @GetMapping("/showNewSaleForm")
    public String showNewSaleForm(Model model) {
        Sale sale = new Sale();
        model.addAttribute("sale", sale);
        return "new_sale";
    }

    //保存数据
    @PostMapping("/saveSale")
    public String saveEmployee(@ModelAttribute("sale") Sale sale) {
        saleService.saveSale(sale);
        return "redirect:/";
    }

    //更新销售数据
    @GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {

        Sale sale = saleService.getSaleId(id);

        model.addAttribute("sale", sale);
        return "update_sale";
    }

    //删除
    @GetMapping("/deleteSale/{id}")
    public String deleteSale(@PathVariable(value = "id") long id) {

        this.saleService.deleteSaleById(id);
        return "redirect:/";
    }

    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;

        Page<Sale> page = saleService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Sale> listSales = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");

        model.addAttribute("listSale", listSales);
        return "index";
    }
}
